<template>
  <div class="system-tenant-container layout-padding">
    <el-card shadow="hover" class="mb15">
      <div class="system-tenant-search">
        <el-input
          v-model="state.tableData.param.filter"
          size="default"
          placeholder="请输入租户名称"
          style="max-width: 180px"
        >
        </el-input>
        <el-button size="default" type="primary" class="ml10" @click="searchTenant">
          <el-icon>
            <ele-Search />
          </el-icon>
          查询
        </el-button>
      </div>
    </el-card>
    <el-card shadow="hover" class="layout-padding-auto">
      <template #header>
        <el-button
          size="default"
          v-auth="'AbpTenantManagement.Tenants.Create'"
          type="success"
          @click="onOpenAddTenant('add')"
        >
          <el-icon>
            <ele-FolderAdd />
          </el-icon>
          新增租户
        </el-button>
      </template>
      <el-table
        :data="state.tableData.data"
        v-loading="state.tableData.loading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column
          prop="name"
          label="租户昵称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              v-auth="'AbpTenantManagement.Tenants.Update'"
              size="small"
              text
              type="primary"
              @click="onOpenAssignMenu(scope.row)"
              >更新菜单</el-button
            >
            <el-button
              v-auth="'AbpTenantManagement.Tenants.Update'"
              size="small"
              text
              type="warning"
              @click="onOpenEditTenant('edit', scope.row)"
              >修改</el-button
            >
            <el-button
              v-auth="'AbpTenantManagement.Tenants.Delete'"
              size="small"
              text
              type="danger"
              @click="onRowDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="onHandleSizeChange"
        @current-change="onHandleCurrentChange"
        class="mt15"
        v-model:current-page="state.tableData.currentPage"
        background
        v-model:page-size="state.tableData.param.maxResultCount"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>
    <tenant-dialog ref="tenantDialogRef" @refresh="getTableData()" />
  </div>
</template>

<script setup lang="ts" name="systemTenant">
import { defineAsyncComponent, reactive, onMounted, ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useTenantApi } from "/@/api/tenant/index";

// 引入组件
const TenantDialog = defineAsyncComponent(
  () => import("/@/views/tenant/components/dialog.vue")
);

// 引入租户 Api 请求接口
const tenantApi = useTenantApi();

// 定义变量内容
const tenantDialogRef = ref();
const state = reactive<SysTenantState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    currentPage: 1,
    param: {
      filter: "",
      sorting: "name",
      skipCount: 0,
      maxResultCount: 10,
    },
  },
});

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  state.tableData.param.skipCount =
    (state.tableData.currentPage - 1) * state.tableData.param.maxResultCount;
  tenantApi
    .getTenantList(state.tableData.param)
    .then((result: any) => {
      state.tableData.total = result.totalCount;
      state.tableData.data = result.items;
      state.tableData.loading = false;
    })
    .catch((err: any) => {
      state.tableData.loading = false;
      console.error("查询租户列表出错：", err);
    });
};

// 搜索
const searchTenant = () => {
  state.tableData.currentPage = 1;
  getTableData();
};

// 打开新增租户弹窗
const onOpenAddTenant = (type: string) => {
  tenantDialogRef.value.openDialog(type);
};

// 更新菜单权限
const onOpenAssignMenu = (row: RowTenantType) => {
  ElMessageBox.confirm(`您确定要更新吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    tenantApi
      .setMenuPermissions(row.id)
      .then((result: any) => {
        if (result) {
          ElMessage.success("更新成功！");
        }
      })
      .catch((err: any) => {
        console.error("赋予菜单权限出错：", err);
      });
  });
};

// 打开修改租户弹窗
const onOpenEditTenant = (type: string, row: RowTenantType) => {
  tenantDialogRef.value.openDialog(type, row);
};

// 删除租户
const onRowDel = (row: RowTenantType) => {
  ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.name}”，是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    tenantApi
      .deleteTenant(row.id)
      .then((result) => {
        if (result) {
          getTableData();
          ElMessage.success("删除成功");
        }
      })
      .catch((err) => {
        console.error("提交出错：", err);
      });
  });
};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.maxResultCount = val;
  getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.currentPage = val;
  state.tableData.param.skipCount =
    (state.tableData.currentPage - 1) * state.tableData.param.maxResultCount;
  getTableData();
};

// 页面加载时
onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.system-tenant-container {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
    .el-table {
      flex: 1;
    }
  }
}
</style>
